package cn.com.fstar.framework.admin.service;

import cn.com.fstar.core.CodeConstant;
import cn.com.fstar.core.model.Tmodule;
import cn.com.fstar.core.model.Trole;
import cn.com.fstar.core.model.Tuser;
import cn.com.fstar.core.pageModel.PageHelper;
import cn.com.fstar.core.pageModel.Role;
import cn.com.fstar.core.pageModel.Tree;
import cn.com.fstar.core.pageModel.User;
import cn.com.fstar.core.util.StringUtil;
import cn.com.fstar.framework.base.dao.BaseDaoI;
import cn.com.fstar.framework.base.model.EasyUIDataGrid;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RoleService {

    @Autowired
    private BaseDaoI<Trole> roleDao;
    @Autowired
    private BaseDaoI<Tuser> userDao;
    @Autowired
    private BaseDaoI<Tmodule> resourceDao;

    public String add(Role role, User user) {

        // 回传信息
        String msg = "";

        // 判断字典编号是否存在
        if (StringUtils.isBlank(role.getId())) {
            role.setId(StringUtil.generateUUID());
        }

        // 用于判断该角色是否已经存在
        Map<String, Object> paramCode = new HashMap<String, Object>();
        paramCode.put("roleName", role.getRoleName().trim());
        if (roleDao.count("select count(*) from Trole t where t.roleName = :roleName", paramCode) > 0) {
            msg = "roleExist";
        } else {
            // 保存TAdmDictionary
            Trole t = new Trole();
            BeanUtils.copyProperties(role, t);

            t.setRoleIsBuildin(CodeConstant.ROLE_ISNOT_BUILDIN);// 内置角色标识
            roleDao.save(t);
            // 刚刚添加的角色，赋予给当前的用户
            Tuser tuser = userDao.get(Tuser.class, user.getId());
            tuser.getTroles().add(t);
            msg = "success";
        }
        return msg;

    }

    public Role get(String id) {
        Role r = new Role();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);
        Trole t = roleDao.get("select distinct t from Trole t left join fetch t.tmodules resource where t.id = :id",
                params);
        if (t != null) {
            BeanUtils.copyProperties(t, r);

            Set<Tmodule> s = t.getTmodules();
            if (s != null && !s.isEmpty()) {
                boolean b = false;
                String ids = "";
                String names = "";
                for (Tmodule tr : s) {
                    if (b) {
                        ids += ",";
                        names += ",";
                    } else {
                        b = true;
                    }
                    ids += tr.getId();
                    names += tr.getModuleName();
                }
                r.setModuleIds(ids);
                r.setModuleNames(names);
            }
        }
        return r;
    }

    public void edit(Role role) {
        Trole t = roleDao.get(Trole.class, role.getId());
        if (t != null) {
            BeanUtils.copyProperties(role, t);
        }
    }

    /**
     * 少量修改，加了个排序，内置字段置顶，费内置字段排序
     * 
     * @param user
     * @param ph
     * @return List<Role>
     */
    public EasyUIDataGrid dataGrid(User user, PageHelper ph) {
       
        List<Role> rl = new ArrayList<Role>();
        List<Trole> tl = null;
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = null;
        
        hql = "from Trole t  order by t.roleIsBuildin desc,t.roleSort asc";

        tl = roleDao.find(hql, params, ph.getPage(), ph.getRows());
        if (tl == null || tl.size() <= 0) {
            return null;
        }

        for (Trole t : tl) {

            Role r = new Role();
            BeanUtils.copyProperties(t, r);
            r.setIconCls("status_online");

            Set<Tmodule> s = t.getTmodules();
            if (s != null && !s.isEmpty()) {
                boolean b = false;
                String ids = "";
                String names = "";
                for (Tmodule tr : s) {
                    if (b) {
                        ids += ",";
                        names += ",";
                    } else {
                        b = true;
                    }
                    ids += tr.getId();
                    names += tr.getModuleName();
                }
                r.setModuleIds(ids);
                r.setModuleNames(names);
            }
            rl.add(r);
        }

        EasyUIDataGrid dg = new EasyUIDataGrid();
        dg.setRows(rl);
        dg.setTotal(roleDao.count("select count(*)" + hql, params));
        return dg;
    }
   
    public void delete(String id) {
        Trole t = roleDao.get(Trole.class, id);
        del(t);
    }

    private void del(Trole t) {
        roleDao.delete(t);
    }

    public List<Tree> tree(User user) {
        List<Trole> l = null;
        List<Tree> lt = new ArrayList<Tree>();

        Map<String, Object> params = new HashMap<String, Object>();
        if (user != null) {
            params.put("userId", user.getId());// 查自己有权限的角色
            l = roleDao.find(
                    "select distinct t from Trole t join fetch t.tusers user where user.id = :userId order by t.roleSort",
                    params);
        } else {
            l = roleDao.find("from Trole t order by t.roleSort");
        }

        if (l != null && l.size() > 0) {
            for (Trole t : l) {
                Tree tree = new Tree();
                BeanUtils.copyProperties(t, tree);
                tree.setText(t.getRoleName());
                tree.setIconCls("status_online");

                lt.add(tree);
            }
        }
        return lt;
    }

    public List<Tree> allTree() {
        return this.tree(null);
    }

    public void grant(Role role) {
        Trole t = roleDao.get(Trole.class, role.getId());
        if (role.getModuleIds() != null && !role.getModuleIds().equalsIgnoreCase("")) {
            String ids = "";
            boolean b = false;
            for (String id : role.getModuleIds().split(",")) {
                if (b) {
                    ids += ",";
                } else {
                    b = true;
                }
                ids += "'" + id + "'";
            }
            t.setTmodules(new HashSet<Tmodule>(
                    resourceDao.find("select distinct t from Tmodule t where t.id in (" + ids + ")")));
        } else {
            t.setTmodules(null);
        }
    }
}
